const Joi = require('joi');
// token生成包
const jwt = require('jsonwebtoken')
const { crypto } = require('../utlis/crypto.js')
const { setLogin, loginBy,loginTo} = require('../model/user.js')

//注册
module.exports.registerPost=async (ctx,next)=>{
    let { user_name, user_password, user_mobile } = ctx.query
    console.log(user_name, user_password, user_mobile)
    // 校验
    const schema = Joi.object({
        user_name: Joi.string()
            .min(3)
            .max(30)
            .required(),
        user_password: Joi.string().required()
            .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
        user_mobile: Joi.string().pattern(/^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/)
    })
    let isJoi = schema.validate({ user_name, user_password, user_mobile });
    // console.log(isJoi);
    if (isJoi.error) {
        ctx.body = {
            status: 0,
            message: isJoi.error.details[0].message
        }
        return
    }
    // 检测用户是否存在
    const rqu = await loginBy(user_mobile)
    // console.log(rqu)
    if (rqu[0]) {
        ctx.body = {
            status: 0,
            message: '用户已从在'
        }
        return
    }
    // 正式注册
   const setLog=await setLogin(user_name, crypto(user_password, process.env.addStack), user_mobile)
    // console.log(setLog.fieldCount)
    if (setLog.fieldCount==0){
        ctx.body = {
            status: 200,
            message: '注册成功'
        }
    }
 }
 //登录
 module.exports.loginByPost=async (ctx,next)=>{
     let { user_name, user_password } = ctx.query
     console.log(ctx.query)
     const rqe = await loginTo(user_name, crypto(user_password, process.env.addStack))
     console.log(rqe[0]);
     if (rqe[0]) {
         // 生成token
         const token = jwt.sign({
             data: {
                 user_name,
                 user_password
             }
         }, process.env.addStack,{ expiresIn: '1h' });

         ctx.body = {
             status: 200,
             token,
             // data: {
             //     user_id:rqe[0].user_id,
             //     user_name,
             //     user_mobile: rqe[0].user_mobile
             // },
             data:rqe[0],
             message: '登录成功'
         }
     } else {
         ctx.body = {
             status: 0,
             message: '登录失败'
         }
     }
 }
